import React, { Component } from 'react';
import "./GoodDetail.scss"
import Data from "../../data/totalData.json"
import headBack from "./images/headBack.jpg"
import { Carousel, Toast } from 'antd-mobile';
import customer from "./images/zxkf.png"
import select from "./images/bottom.png"
import cart from "./images/cart.png"
import active from "./images/active.png"
class goodsDetail extends Component {
  constructor(props) {
    super(props)
    console.log(props)
    this.cid = props.match.params.cid
    this.id = props.match.params.id
  }
  state = {
    detail: "",//商品详情
    swiper: [],//轮播
    pictures: [],//图文区域
    showCollect: false, //收藏标志位
  }
  componentDidMount () {
    Data.forEach(val => {
      if (val.cid == this.cid && val.id == this.id) {
        this.setState({
          detail: val,
          swiper: val.imgDetail,
          pictures: val.detail
        })
        // console.log(val)
        // console.log(val.imgDetail)
        // console.log(val.detail);
      }
    })
    // 进入某个商品详情的时候判断是否被收藏过
    let collection_str = localStorage.getItem("collections")
    let collections = JSON.parse(collection_str) || []
    let index = collections.findIndex(val => {
      if (val.id == this.id && val.cid == this.cid) {
        return true
      }
    })
    if (index !== -1) {
      this.setState({
        showCollect: true
      })
    }
  }
  // 收藏功能
  handleCollect = (params) => {
    // 获取token
    let token = localStorage.getItem("token")
    if (!token) {
      this.props.history.push("/Login")
      return false
    }
    // collections 代表的是收藏的数据 是一个数组 存在本地缓存中
    let collections_str = localStorage.getItem("collections")
    // 将字符串转换为对象 不存在缓存的时候给个空数组
    let collections = JSON.parse(collections_str) || []
    //遍历缓存(收藏)，看是否存在该商品
    let index = collections.findIndex(val => {
      if (val.id == this.id && val.cid == this.cid) {
        return true
      }
    })
    if (index !== -1) {  //返回的索引结果为-1 表示不存在
      // 存在 再次点击就是取消收藏
      collections.splice(index, 1)
      this.setState({
        showCollect: false
      })
      Toast.info('取消收藏成功', 1);
    } else {
      // 不存在 点击为加入收藏
      let detail = this.state.detail
      detail.num = 1
      detail.checked = true
      collections.push(detail)
      this.setState({
        showCollect: true
      })
      Toast.info('收藏成功', 1);
    }
    // 每次操作后都要更新缓存重新设置
    localStorage.setItem("collections", JSON.stringify(collections))
  }
  //跳转购物车
  handleCart = (params) => {
    this.props.history.push("/cart")
  }
  // 加入购物车功能
  handleAddCart = (params) => {
    // 获取token
    let token = localStorage.getItem("token")
    if (!token) {
      this.props.history.push("/Login")
      return false
    }
    // 从本地缓存里获取购物车的数据
    let carts_str = localStorage.getItem("carts")
    let carts = JSON.parse(carts_str) || []
    let index = carts.findIndex(val => {
      if (val.id == this.id && val.cid == this.cid) {
        return true
      }
    })
    // 判断当前商品是否在购物车里面
    if (index == -1) {
      let detail = this.state.detail
      detail.num = 1
      detail.checked = true
      carts.push(detail)
    } else {
      carts[index].num++
    }
    localStorage.setItem("carts", JSON.stringify(carts))
    Toast.info('加入购物车成功', 1);
  }
  // 立即购买
  handleToBuy = (params) => {
    // 获取token
    let token = localStorage.getItem("token")
    if (!token) {
      this.props.history.push("/Login")
      return false
    }
    let buyNow_str = this.state.detail
    buyNow_str.num = 1
    buyNow_str.checked = true
    let buyNow = []
    buyNow.push(buyNow_str)
    localStorage.setItem("buyNow", JSON.stringify(buyNow))
    this.props.history.push("/pay")
  }
  render () {
    return (
      <div className="GoodDetail">
        {/* 头部导航开始 */}
        <div className="categoryTop">
          <img src={headBack} alt="返回" onClick={() => window.history.go(-1)} />
          <p className="title">商品详情</p>
          <p className="lie"></p>
        </div>
        {/* 头部导航结束 */}
        {/* 轮播开始 */}
        <div className="swiper">
          {this.state.swiper && <Carousel
            autoplay={true}
            infinite
          >
            {this.state.swiper.map(val => (
              val ? <div className="images"
                key={val}
              >
                <img
                  src={`${val}.jpg`}
                  alt={val}
                  style={{ width: '100%', verticalAlign: 'top' }}
                  onLoad={() => {
                    // fire window resize event to change height
                    window.dispatchEvent(new Event('resize'));
                    this.setState({ imgHeight: 'auto' });
                  }}
                />
              </div> : <div key={val}></div>
            ))}
          </Carousel>}
        </div>
        {/* 轮播结束 */}
        <div className="tit">{this.state.detail.name}</div>
        <div className="price">￥{this.state.detail.price}</div>
        {/* 图文区域开始 */}
        <div className="more">
          <div className="hot">商品热点</div>
          <div className="pics">
            {
              this.state.pictures.map(val => {
                return val ? <div className="picItem" key={val}>
                  <img src={`${val}.jpg`} alt={val} />
                </div> : <div key={val}></div>
              })
            }
          </div>
        </div>
        {/* 图文区域结束 */}
        {/* 底部功能区开始 */}
        <div className="buttons">
          <div className="customer">
            <img src={customer} alt="客服" />
          </div>
          <div className="select" onClick={this.handleCollect}>
            {this.state.showCollect ? <img src={active} alt="收藏" /> : <img src={select} alt="收藏" />}
          </div>
          <div className="cart" onClick={this.handleCart}>
            <img src={cart} alt="购物车" />
          </div>
          <div className="add" onClick={this.handleAddCart}>加入购车</div>
          <div className="buy" onClick={this.handleToBuy}>立即购买</div>
        </div>
        {/* 底部功能区结束 */}
      </div>
    );
  } y
}

export default goodsDetail;